package com.propertyportal.propertylistfragment;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.propertyportal.manageproperty.R;

public class EditProperty extends SherlockFragment {
	private EditText pname;
	private EditText address;
	private EditText price;
	private EditText description;
	private EditText longitude;
	private EditText latitude;
	private Spinner propertyType;
	private Spinner sellingType;
	private Button edit;
	private TextView statusText;
	private Spinner status;
	public final static String ARG_POSITION = "position";
	public static int mCurrentPosition = -1;
	public String returnedString = "";
	private SherlockFragmentActivity fa;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		if (savedInstanceState != null) {
			mCurrentPosition = savedInstanceState.getInt(ARG_POSITION);
		}
		fa = (SherlockFragmentActivity) super.getActivity();
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.addproperty, container, false);
		pname = (EditText) view.findViewById(R.id.Pname);
		address = (EditText) view.findViewById(R.id.address);
		price = (EditText) view.findViewById(R.id.price);
		description = (EditText) view.findViewById(R.id.description);
		longitude = (EditText) view.findViewById(R.id.longitude);
		latitude = (EditText) view.findViewById(R.id.latitude);
		propertyType = (Spinner) view.findViewById(R.id.propertytype);
		sellingType = (Spinner) view.findViewById(R.id.propertyselling);
		statusText = (TextView) view.findViewById(R.id.statustext);
		status = (Spinner) view.findViewById(R.id.propertystatus);
		edit = (Button) view.findViewById(R.id.addproperty);
		edit.setText("Save");

		edit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				new updateData().execute();
			}
		});
		statusText.setVisibility(View.VISIBLE);
		status.setVisibility(View.VISIBLE);

		setHasOptionsMenu(true);
		return view;
	}

	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		Bundle args = getArguments();
		if (args != null) {
			displayData(args.getInt(ARG_POSITION));

		}
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		// TODO Auto-generated method stub
		super.onCreateOptionsMenu(menu, inflater);
		menu.clear();
		inflater.inflate(R.menu.add, menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.back:
			FragmentManager fm = getActivity().getSupportFragmentManager();
			fm.popBackStack();
			return true;
		default:

			return super.onOptionsItemSelected(item);
		}

	}

	public void displayData(int position) {

		price.setText(PropertyList.property.get(position).getPrice());
		pname.setText(PropertyList.property.get(position).getName());
		longitude.setText(PropertyList.property.get(position).getLongitude());
		latitude.setText(PropertyList.property.get(position).getLatitude());
		description.setText(PropertyList.property.get(position)
				.getDescription());
		address.setText(PropertyList.property.get(position).getAddress());
		propertyType.setSelection(4);
		sellingType.setSelection(2);
		status.setSelection(0);
		mCurrentPosition = position;

	}

	public void updateData() {
		String urls = "http://192.168.2.38:8080/STTHERESEREALTYWS/webresources/com.propertyportal.entities.property/updateProperty/";
		int id = PropertyList.property.get(mCurrentPosition).getPropertyId();

		try {
			URL url = new URL(urls
					+ id
					+ "/"
					+ URLEncoder.encode(pname.getText().toString().trim(),
							"ISO-8859-1")
					+ "/"
					+ URLEncoder.encode(
							description.getText().toString().trim(),
							"ISO-8859-1")
					+ "/"
					+ URLEncoder.encode(price.getText().toString().trim(),
							"ISO-8859-1")
					+ "/"
					+ propertyType.getSelectedItemPosition()
					+ "/"
					+ sellingType.getSelectedItemPosition()
					+ "/"
					+ status.getSelectedItemPosition()
					+ "/"
					+ URLEncoder.encode(address.getText().toString().trim(),
							"ISO-8859-1") + "/"
					+ longitude.getText().toString() + "/"
					+ latitude.getText().toString());
			// URL url = new URL(urla+from+"/"+to);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Content-Type", "application/json");
			if (conn.getResponseCode() != 200) {
				throw new RuntimeException("Failed : HTTP error code : "
						+ conn.getResponseCode());
			} else {
				System.out.print("Succes");
			}

			BufferedReader br = new BufferedReader(new InputStreamReader(
					(conn.getInputStream())));

			String output;
			System.out.println("Output from Server .... \n");
			while ((output = br.readLine()) != null) {
				System.out.println(output);
				returnedString = output;
			}

			conn.disconnect();

		} catch (MalformedURLException e) {

			e.printStackTrace();

		} catch (IOException e) {
			System.out.println(e.getMessage());
		}

	}

	private class updateData extends AsyncTask<Void, Void, Void> {

		private ProgressDialog dialog = new ProgressDialog(fa);

		protected void onPreExecute() {

			dialog.setMessage("Loading...");
			dialog.show();
		}

		@Override
		protected Void doInBackground(final Void... unused) {

			try {
				updateData();

			} catch (Exception e) {
				Log.e("", "wala jud ma add", e);
			}
			return null;
		}

		protected void onPostExecute(Void result) {
			if (this.dialog != null) {
				this.dialog.dismiss();
			}
			Toast.makeText(getActivity(), returnedString, Toast.LENGTH_LONG)
					.show();
			FragmentManager fm = getActivity().getSupportFragmentManager();

			fm.popBackStack();

		}

	}
}
